#include "stdafx.h"
#include "EquipmentListVM.h"
#include "moc_EquipmentListVM.cpp"
#include "EquipmentModel.h"

#pragma region Constructor

EquipmentListVM::EquipmentListVM(QList<EquipmentModel*> * model)
	:_model(model)
{
}


EquipmentListVM::~EquipmentListVM(void)
{
}

#pragma endregion

QVariant EquipmentListVM::headerData(int section, Qt::Orientation orientation, int role) const
{
	if (role != Qt::DisplayRole)
		return QVariant();
 
	if (orientation == Qt::Horizontal) 
	{
		switch (section)
		{
		case 0: return tr("Count");
		case 1: return tr("Value");
		case 2: return tr("Ref");
		case 3: return tr("Name");
		}
	}

	return QVariant();
}

int EquipmentListVM::rowCount(const QModelIndex & parent) const
{
	return _model->count() + 1; // Always leave a blank row at the end.
}

int EquipmentListVM::columnCount(const QModelIndex & parent) const
{
	return 4;
}

QVariant EquipmentListVM::data(const QModelIndex & index, int role) const
{
	if (role != Qt::DisplayRole && role != Qt::EditRole)
		return QVariant();

	if (index.row() > _model->count() - 1)
		return QVariant();

	EquipmentModel * Equipment = _model->at(index.row());

	switch (index.column())
	{
	case 0: return Equipment->Count();
	case 1: return Equipment->Value();
	case 2: return Equipment->Reference();
	case 3: return Equipment->Name();
	}
	
	return QVariant();
}

bool EquipmentListVM::setData(const QModelIndex & index, const QVariant & value, int role)
{
	if (role != Qt::EditRole)
		return false;

	if (index.row() > _model->count() - 1)
		insertRow(_model->count());

	EquipmentModel * Equipment = _model->at(index.row());

	bool success = false;

	switch (index.column())
	{
	case 0: Equipment->setCount(value.toInt()); success = true; break;
	case 1: Equipment->setValue(value.toString()); success = true; break;
	case 2: Equipment->setReference(value.toString()); success = true; break;
	case 3: Equipment->setName(value.toString()); success = true; break;
	}

	return success;
}

Qt::ItemFlags EquipmentListVM::flags(const QModelIndex & index) const
{
	return base::flags(index) | Qt::ItemIsEditable;
}

bool EquipmentListVM::insertRows(int row, int count, const QModelIndex & parent)
{
	beginInsertRows(parent, row, row + count - 1);

	for (int i = row; i < row + count; i++)
		_model->insert(i,new EquipmentModel());

	endInsertRows();

	return true;
}

bool EquipmentListVM::removeRows(int row, int count, const QModelIndex & parent)
{
	beginRemoveRows(parent, row, row + count  - 1);

	int nrows = _model->count();

	for (int i = row + count - 1; i >= row ; i--)
	{
		if (i < nrows)
			delete _model->takeAt(i);
	}

	endRemoveRows();

	return true;
}

